package com.china08.yxyapi.service.yxyresource.statistics.impl;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.StringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket;
import org.elasticsearch.search.aggregations.bucket.terms.TermsBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.stereotype.Service;

import com.china08.yxyapi.entity.db.res.YxyResPhase;
import com.china08.yxyapi.repository.db.YxyResPhaseRepository;
import com.china08.yxyapi.service.yxyresource.statistics.ResourceTypeCountService;

@Service
public class ResourceTypeCountServiceImpl implements ResourceTypeCountService {
    @Autowired
    private ElasticsearchTemplate et;

    @Autowired
    private YxyResPhaseRepository yxyResPhaseRepository;

    @Override
    public Map<String, Object> statisticsResourceTypeCount(String districtCode) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        TermQueryBuilder builderType2 = new TermQueryBuilder("typeId", "yx14");
        boolQueryBuilder.mustNot(builderType2);
        TermQueryBuilder builderTypeDe = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.mustNot(builderTypeDe);
        SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
        searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
        TermsBuilder gradeTermsBuilder = AggregationBuilders.terms("phaseIdAgg").field("formatId").size(100);
        searchRequestBuilder.addAggregation(gradeTermsBuilder);
        SearchResponse sr = searchRequestBuilder.setQuery(boolQueryBuilder).execute().actionGet();
        Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
        StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
        Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();

        // 返回
        Map<String, Object> map = new HashMap<String, Object>();
        while (gradeBucketIt.hasNext()) {
            Bucket gradeBucket = gradeBucketIt.next();
            String key = (String) gradeBucket.getKey();
            long value = gradeBucket.getDocCount();
            map.put(key, value);

            System.out.println(key + "资源类型有" + value + "个资源。");
            System.out.println();
        }
        return map;
    }

    @Override
    public Map<String, Object> statisticsResourcePhaseCount(String xueduan, Integer schoolBureauLevel, String districtCode) {
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        TermQueryBuilder builderType = new TermQueryBuilder("typeId", "yx14");
        boolQueryBuilder.mustNot(builderType);
        TermQueryBuilder builderTypeDe = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderTypeDe);
        TermQueryBuilder builderDel = null;
        if (schoolBureauLevel == 0) {
            builderDel = new TermQueryBuilder("districtCode", districtCode);

        } else if (schoolBureauLevel == 1) {
            builderDel = new TermQueryBuilder("cityCode", districtCode);
        } else if (schoolBureauLevel == 2) {
            builderDel = new TermQueryBuilder("provinceCode", districtCode);
        }
        boolQueryBuilder.must(builderDel);

        // 1.将学段名称转换成代码
        YxyResPhase yxyResPhase = yxyResPhaseRepository.findByName(xueduan);
        // 返回
        Map<String, Object> map = new HashMap<String, Object>();
        if (yxyResPhase != null && !yxyResPhase.getId().equals("")) {

            // 2.根据学段id查询记录
            TermQueryBuilder builderType2 = new TermQueryBuilder("phaseIdList", yxyResPhase.getId());
            boolQueryBuilder.must(builderType2);

            SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
            searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
            TermsBuilder gradeTermsBuilder = AggregationBuilders.terms("phaseIdAgg").field("formatId").size(100);
            searchRequestBuilder.addAggregation(gradeTermsBuilder);
            SearchResponse sr = searchRequestBuilder.setQuery(boolQueryBuilder).execute().actionGet();
            Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
            StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
            Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();
            while (gradeBucketIt.hasNext()) {
                Bucket gradeBucket = gradeBucketIt.next();
                String key = (String) gradeBucket.getKey();
                long value = gradeBucket.getDocCount();
                map.put(key, value);

                System.out.println(key + "类型有" + value + "个资源。");
                System.out.println();
            }
        }
        return map;
    }

    // 教育局平台办公 资源统计 饼状图 资源类型(学段为空)
    @Override
    public Map<String, Object> resourceTypeCount(String districtCode) {

        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        TermQueryBuilder builderTypeDe = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderTypeDe);
        SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
        searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
        TermsBuilder gradeTermsBuilder = AggregationBuilders.terms("phaseIdAgg").field("formatId").size(100);
        searchRequestBuilder.addAggregation(gradeTermsBuilder);
        SearchResponse sr = searchRequestBuilder.setQuery(boolQueryBuilder).execute().actionGet();
        Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
        StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
        Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();

        // 返回
        Map<String, Object> map = new HashMap<String, Object>();
        while (gradeBucketIt.hasNext()) {
            Bucket gradeBucket = gradeBucketIt.next();
            String key = (String) gradeBucket.getKey();
            long value = gradeBucket.getDocCount();
            map.put(key, value);

            System.out.println(key + "资源类型有" + value + "个资源。");
            System.out.println();
        }
        return map;
    }

    // 教育局平台办公 资源统计 饼状图 资源类型(学段不为空)
    @Override
    public Map<String, Long> resourceTypeCount(String stageName, Integer schoolBureauLevel, String districtCode) {

        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        TermQueryBuilder builderTypeDe = new TermQueryBuilder("isDelete", 0);
        boolQueryBuilder.must(builderTypeDe);
        TermQueryBuilder builderDel = null;
        if (schoolBureauLevel == 0) {
            builderDel = new TermQueryBuilder("districtCode", districtCode);

        } else if (schoolBureauLevel == 1) {
            builderDel = new TermQueryBuilder("cityCode", districtCode);
        } else if (schoolBureauLevel == 2) {
            builderDel = new TermQueryBuilder("provinceCode", districtCode);
        }
        boolQueryBuilder.must(builderDel);

        // 1.将学段名称转换成代码
        YxyResPhase yxyResPhase = yxyResPhaseRepository.findByName(stageName);
        // 返回
        Map<String, Long> map = new HashMap<String, Long>();
        if (yxyResPhase != null && !yxyResPhase.getId().equals("")) {

            // 2.根据学段id查询记录

            BoolQueryBuilder knoBuilder = new BoolQueryBuilder();
            TermQueryBuilder builderType2 = new TermQueryBuilder("phaseIdList", yxyResPhase.getId());
            TermQueryBuilder builderType3 = new TermQueryBuilder("stage", yxyResPhase.getId());
            knoBuilder.should(builderType2);
            knoBuilder.should(builderType3);
            boolQueryBuilder.must(knoBuilder);

            SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
            searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);

            TermsBuilder gradeTermsBuilder = AggregationBuilders.terms("phaseIdAgg").field("typeId").size(100);
            TermsBuilder gradeTermsBuilder2 = AggregationBuilders.terms("stage").field("weikeSubject").size(100);

            // SearchResponse sr =
            // searchRequestBuilder.setQuery(boolQueryBuilder).execute().actionGet();
            SearchResponse sr = searchRequestBuilder.setQuery(boolQueryBuilder).addAggregation(gradeTermsBuilder).addAggregation(gradeTermsBuilder2).execute().actionGet();

            Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
            StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
            Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();
            while (gradeBucketIt.hasNext()) {
                Bucket gradeBucket = gradeBucketIt.next();
                String key = (String) gradeBucket.getKey();
                System.out.println("key:" + key);
                long value = gradeBucket.getDocCount();
                map.put(key, value);
                System.out.println(key + "科目有" + value + "个资源。");
                System.out.println();
            }

            StringTerms gradeTerms1 = (StringTerms) aggMap.get("stage");
            Iterator<Bucket> gradeBucketIt1 = gradeTerms1.getBuckets().iterator();
            while (gradeBucketIt1.hasNext()) {
                Bucket gradeBucket = gradeBucketIt1.next();
                String key = (String) gradeBucket.getKey();
                System.out.println("key:" + key);
                long value = gradeBucket.getDocCount();
                map.put(key, map.get(key) != null ? map.get(key) + value : value);
                System.out.println(key + "科目有" + value + "个微克。");
                System.out.println();
            }
        } else {
            SearchRequestBuilder searchRequestBuilder = et.getClient().prepareSearch("yxy_res").setTypes("resource");
            searchRequestBuilder.setSearchType(SearchType.QUERY_THEN_FETCH);
            TermsBuilder gradeTermsBuilder = AggregationBuilders.terms("phaseIdAgg").field("typeId").size(100);
            searchRequestBuilder.addAggregation(gradeTermsBuilder);
            SearchResponse sr = searchRequestBuilder.setQuery(boolQueryBuilder).execute().actionGet();
            Map<String, Aggregation> aggMap = sr.getAggregations().asMap();
            StringTerms gradeTerms = (StringTerms) aggMap.get("phaseIdAgg");
            Iterator<Bucket> gradeBucketIt = gradeTerms.getBuckets().iterator();
            while (gradeBucketIt.hasNext()) {
                Bucket gradeBucket = gradeBucketIt.next();
                String key = (String) gradeBucket.getKey();
                long value = gradeBucket.getDocCount();
                map.put(key, value);

                System.out.println(key + "类型有" + value + "个资源。");
                System.out.println();
            }
        }
        return map;
    }
}
